package view;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JTextField;

import xl.Address;

import model.Cell;
import model.CurrentSlot;
import model.Sheet;

public class Editor extends JTextField implements ActionListener, Observer {
	private Sheet sheet;
	private Address currentAddress;
	private CurrentSlot currentSlot;
	private StatusArea statusArea;

	public Editor(Sheet sheet, CurrentSlot currentSlot, StatusArea statusArea) {
		setBackground(Color.WHITE);
		addActionListener(this);
		this.sheet = sheet;
		this.currentSlot = currentSlot;
		this.statusArea = statusArea;
	}

	public void actionPerformed(ActionEvent event) {
		try {
			sheet.put(currentAddress, this.getText());
			statusArea.setText("");
			sheet.updateEverything();
		} catch (Exception e) {
			statusArea.setText(e.getMessage());
		}
		String contents = currentSlot.getCurrent().getText();
		try {
			contents = sheet.getParsedCell(currentAddress);
		} catch (Exception e) { /* Ignore */ }
		currentSlot.updateContents(contents);
	}

	public void update(Observable o, Object arg) {
		if (arg instanceof Address) {
			currentAddress = (Address)arg;
			Cell markedCell = sheet.getCell(currentAddress);
			if (markedCell == null) {
				setText("");
			} else {
				setText(markedCell.toString());
			}
		}
	}
}